package cn.edu.swufe.stu2025.rateexample;

import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.util.Log;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import cn.edu.swufe.stu2025.rateexample.ExchangeRate;
import cn.edu.swufe.stu2025.rateexample.ExchangeRateAdapter;

public class MainActivity extends AppCompatActivity {
    private String TAG = "add";
    private RecyclerView recyclerView;
    Handler handler;
    private ExchangeRateAdapter adapter;
    private List<ExchangeRate> exchangeRates = new ArrayList<>();
    String html=" ";
    Bundle retbundle = new Bundle();
    ArrayList<String> list = new ArrayList<>();
    private  String logDate = "";
    private final String DATE_SP_KEY = "lastRateDateStr";


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        SharedPreferences sp =getSharedPreferences("myrate",Context.MODE_PRIVATE);
        logDate = sp.getString(DATE_SP_KEY,"");
        Log.i(TAG, "onCreate: sp内日期为："+ logDate);

        recyclerView = findViewById(R.id.recyclerView);
        recyclerView.setLayoutManager(new LinearLayoutManager(this));
        adapter = new ExchangeRateAdapter(exchangeRates);
        recyclerView.setAdapter(adapter);
        //发送信息
        handler = new Handler(Looper.getMainLooper(), msg -> {
            if (msg.what == 5) {
                Bundle bundle = (Bundle) msg.obj;
                List<String> data = bundle.getStringArrayList("mylist");
                exchangeRates.clear();
                for (String item : data) {
                    String[] parts = item.split("->");
                    exchangeRates.add(new ExchangeRate(parts[0], Double.parseDouble(parts[1])));
                }
                adapter.notifyDataSetChanged();
            }
            return true;
        });

        fetchExchangeRates();
    }

    private void fetchExchangeRates() {
        String curDateStr = (new SimpleDateFormat("yyyy-MM-dd")).format(new Date());
        Log.i(TAG, "fetchExchangeRates: 当前日期为："+curDateStr);

            new Thread(() -> {

                if(!curDateStr.equals(logDate)){
                    //不获取
                    try{
                    Log.i(TAG, "fetchExchangeRates: 日期相等，不获取数据");
                    DBManager dbManager = new DBManager(MainActivity.this);//注意this
                    for (RateItem rateItem :dbManager.listALL()){
                        String ss = rateItem.getCurName()+"=>" +rateItem.getCurRate();
                        Log.i(TAG, "fetchExchangeRates: "+ss);
                        list.add(ss);
                    }
                    Log.i(TAG, "MyTask:run:bundle=" + retbundle);
                    // 发送消息
                    retbundle.putStringArrayList("mylist", list);
                    Message msg = handler.obtainMessage(5, retbundle);
                    handler.sendMessage(msg);
                    } catch (Exception e) {
                        Log.e(TAG, "设备时间异常或其他错误", e);
                        e.printStackTrace();
                    }
                }
                else {//获取数据
                    // Log.i(TAG, "fetchExchangeRates: 日期不相等，获取数据线程开启");
                    try {
                        // 获取 HTML 页面
                        Log.i(TAG, "fetchExchangeRates: 进入try中");
                        Document doc = Jsoup.connect("https://www.huilvbiao.com/bank/spdb").get();
                        Log.i(TAG, "fetchExchangeRates: 以获取网络数据：");
                        //修改时间
                        SharedPreferences sp = getSharedPreferences("myrate", Context.MODE_PRIVATE);
                        SharedPreferences.Editor edit = sp.edit();
                        edit.putString(DATE_SP_KEY,curDateStr);
                        edit.commit();
                        Log.i(TAG, "fetchExchangeRates: 日期更新结束，新日期为"+curDateStr);
                        // 创建新数组，向数据库中传入数据
                        List<RateItem> rateList = new ArrayList<RateItem>();

                        Element table = doc.selectFirst("table");
                        Elements rows = table.select("tr");
                        Log.i(TAG, "fetchExchangeRates: " + table);
                        rows.remove(0); // 移除表头
                        for (Element row : rows) {
                            Elements tds = row.getElementsByTag("td");
                            Elements spans = row.getElementsByTag("span");
                            //Log.i(TAG, "fetchExchangeRates: "+tds );
                            //Log.i(TAG, "fetchExchangeRates: "+ spans);
                            // 检查列数是否足够
                            if (tds.size() >= 4) {
                                //Element t1 = tds.first();
                                Element t1 = spans.first();
                                Element t2 = tds.get(2);
                                String str1 = t1.text().trim();
                                String str2 = t2.text().trim();

                                //加入数据库数组
                                rateList.add(new RateItem(str1,str2));

                                Log.i(TAG, "run:td1=" + str1 + "->" + str2);
                                html += (str1 + "->" + str2 + "\n");
                                list.add(str1 + "->" + str2);
                            }
                            else {
                                Log.w(TAG, "表格行列数不足，跳过该行");
                            }
                        }

                        Log.i(TAG, "fetchExchangeRates: 数据获取完毕");
                        DBManager dbManager = new DBManager(MainActivity.this);
                        dbManager.deleteAll();
                        Log.i(TAG, "fetchExchangeRates: 删除所有元素");
                        dbManager.addAll(rateList);
                        Log.i(TAG, "fetchExchangeRates: 加入新元素");

                        Log.i(TAG, "MyTask:run:bundle=" + retbundle);
                        // 发送消息
                        retbundle.putStringArrayList("mylist", list);
                        Message msg = handler.obtainMessage(5, retbundle);
                        handler.sendMessage(msg);

                    } catch (Exception e) {//从网页中获取数据
                        Log.e(TAG, "设备时间异常或其他错误", e);
                        e.printStackTrace();
                    }
                }

            }).start();

    }
}